package com.apes.hr.paySupport.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.MapUtil;
import com.apes.hr.paySupport.model.SupportApplication;
import com.apes.hr.paySupport.model.SupportApplicationAffirm;
import com.apes.hr.paySupport.model.SupportApplicationExecution;
import com.apes.hr.paySupport.model.SupportApplicationItem;
import com.apes.hr.paySupport.repository.SupportApplicationExecutionRepository;
import com.apes.hr.paySupport.repository.SupportApplicationItemRepository;
import com.apes.hr.paySupport.repository.SupportApplicationRepository;
import com.apes.hr.transfer.model.TransferApplicationItem;
import com.apes.hr.transfer.repository.TransferApplicationItemRepository;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.rbac.model.LocalPermitItem;
import com.apes.scm.rbac.repository.LocalPermitItemRepository;
import com.apes.scm.rbac.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Title: SupportApplicationExecutionService
 * @Description: 付费支援单执行
 * @author: ZhengZeXian
 * @create: 2021/4/21 10:36
 */
@Service("hrSupportApplicationExecutionService")
public class SupportApplicationExecutionService extends DomainService {

    @Autowired
    private PostRepository postRepository;
    @Autowired
    private LocalPermitItemRepository localPermitItemRepository;
    @Autowired
    private DeptRepository deptRepository;
    @Autowired
    private SupportApplicationExecutionRepository supportApplicationExecutionRepository;
    @Autowired
    private SupportApplicationService supportApplicationService;
    @Autowired
    private SupportApplicationItemRepository supportApplicationItemRepository;
    @Autowired
    private SupportApplicationRepository supportApplicationRepository;
    @Autowired
    private SupportApplicationAffirmService supportApplicationAffirmService;
    @Autowired
    private EnumerationRepository enumerationRepository;
    @Autowired
    private TransferApplicationItemRepository transferApplicationItemRepository;

    /**
     * 查询门店编制 控制部门查询权限
     * @param request
     * @return
     */
    public com.apestech.framework.json.JSONObject staffing(SimpleRequest request){
        com.apestech.framework.json.JSONObject json = new com.apestech.framework.json.JSONObject();
        List<LocalPermitItem> localPermitItems = localPermitItemRepository.find(request.getPostId(), "pp_search", "pt_dept");
        try {
            String body = request.getData().toString();
            json = com.apestech.framework.json.JSON.toJSON(body);
            if (!localPermitItems.isEmpty()){
                Dept dept = deptRepository.findOne(localPermitItems.get(0).getOrgId());
                if (dept != null) json.put("BRANCH_ID",dept.getBranch().getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    public SupportApplicationExecution findById(SimpleRequest request){
        String support_execution_id = request.get("SUPPORT_EXECUTION_ID");
        return supportApplicationExecutionRepository.findOne(support_execution_id);
    }

    /**
     * 查询支援人员确认单明细
     */
    public com.apestech.framework.json.JSONObject affirmApplication(SimpleRequest request) throws Exception {
        JSONObject jo = request.getJO();
        JSONArray condition = jo.getJSONArray("condition");
        if (condition != null) {
            for (int i = 0; i < condition.size(); i++) {
                if ("SUPPORT_DATE".equals(condition.getJSONObject(i).getString("field"))){
                    JSONObject json = new JSONObject();
                    if("GTE".equals(condition.getJSONObject(i).getString("operator"))){
                        json.put("field","START_DATE");
                        json.put("operator","GTE");
                        json.put("value",condition.getJSONObject(i).getString("value"));
                        json.put("type","date");
                        condition.add(json);
                    }else if("LTE".equals(condition.getJSONObject(i).getString("operator"))){
                        json.put("field","END_DATE");
                        json.put("operator","LTE");
                        json.put("value",condition.getJSONObject(i).getString("value"));
                        json.put("type","date");
                        condition.add(json);
                    }
                }
            }
            jo.put("condition", condition);
        }
        List<LocalPermitItem> localPermitItems = localPermitItemRepository.find(request.getPostId(), "pp_search", "pt_dept");
        String body = request.getData().toString();
        if (!localPermitItems.isEmpty()) {
            Dept dept = deptRepository.findOne(localPermitItems.get(0).getOrgId());
            if (dept != null){
                JSONObject json = new JSONObject();
                json.put("field","BRANCH_QX");
                json.put("operator","EQ");
                json.put("value",dept.getBranch().getId());
                condition.add(json);
            }
        }
        return com.apestech.framework.json.JSON.toJSON(jo.toJSONString());
    }

    /**
     * 终止和延期 修改结束时间
     * @param request
     * @return
     */
    public Map updateEndDate(SimpleRequest request){
        //获取参数
        String id = request.get("id");
        Date endDate = DateUtil.parse(request.get("endDate"));
        JSONObject object = request.get("endTime");
        String endTime = object.get("code").toString();
        String userId = request.get("userId")+"";

        SupportApplicationExecution execution = supportApplicationExecutionRepository.findOne(id);
        Date dDate = new Date();
        execution.setEndDatePre(endDate);
        execution.setEndTimePre(enumerationRepository.findByCodeAndValidIsTrue(endTime));

        if (execution.getStartTime().getCode().equals("AM")){
            execution.setStartDate(DateUtil.parse( DateUtil.format(execution.getStartDate(),DateUtil.SHOW_DATE_FORMAT)+" 06:00:00",DateUtil.SHOW_DATETIME_FORMAT));
        }
        if (execution.getStartTime().getCode().equals("PM")){
            execution.setStartDate(DateUtil.parse( DateUtil.format(execution.getStartDate(),DateUtil.SHOW_DATE_FORMAT)+" 12:00:00",DateUtil.SHOW_DATETIME_FORMAT));
        }

        if (execution.getEndTimePre().getCode().equals("AM")){
            execution.setEndDatePre(DateUtil.parse( DateUtil.format(endDate,DateUtil.SHOW_DATE_FORMAT)+" 12:00:00",DateUtil.SHOW_DATETIME_FORMAT));
        }
        if (execution.getEndTimePre().getCode().equals("PM")){
            execution.setEndDatePre(DateUtil.parse( DateUtil.format(endDate,DateUtil.SHOW_DATE_FORMAT)+" 23:59:59",DateUtil.SHOW_DATETIME_FORMAT));
        }

        //结束日期大于开始日期为终止单据作废
        if(execution.getEndDatePre().getTime() > execution.getStartDate().getTime()){
            //检查时间是否冲突
            checkSupportClash(execution);
        }

        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date dToday= formatter.parse(formatter.format(dDate),new ParsePosition(0));

        Map map = supportApplicationAffirmService.getApproveUserIds(execution.getSupportApplicationItem().getSupportApplication());
        execution.setCandidates(map.get("candidates").toString());   //设置OA候选人
        execution.setSign(map.get("operation").toString());
        execution.setProcessInitiator("1");

//        if (dToday.getTime() <= endDate.getTime()) {
//
//        } else {
//            throw new RuntimeException("超过可终止时间!!!");
//        }
        supportApplicationExecutionRepository.saveAndFlush(execution);
        return MapUtil.mapped(execution);
    }

    /**
     * 延期或者终止审核通过
     * @return
     */
    public SupportApplicationExecution approvePass(SimpleRequest request){
        Date date = new Date();
        GregorianCalendar ca = new GregorianCalendar();
        int i = ca.get(GregorianCalendar.AM_PM);
        String time = i == 0 ? "AM" :"PM";

        SupportApplicationExecution exec = request.getO(SupportApplicationExecution.class);
        if (exec.getEndTimePre().getCode().equals("AM")){
            exec.setEndDate(DateUtil.parse( DateUtil.format(exec.getEndDatePre(),DateUtil.SHOW_DATE_FORMAT)+" 12:00:00",DateUtil.SHOW_DATETIME_FORMAT));
        }
        if (exec.getEndTimePre().getCode().equals("PM")){
            exec.setEndDate(DateUtil.parse( DateUtil.format(exec.getEndDatePre(),DateUtil.SHOW_DATE_FORMAT)+" 23:59:59",DateUtil.SHOW_DATETIME_FORMAT));
        }
        exec.setEndTime(exec.getEndTimePre());
        //算出相差的天数 减1 开始当天和结束当天不算，后面计算
        long betweenDays = (exec.getEndDate().getTime() - exec.getStartDate().getTime()) / (1000L*3600L*24L) - 1;
        //修改后的实际支援时长
        double day = supportApplicationAffirmService.calculateDay(betweenDays, exec.getStartTime().getCode(), exec.getEndTime().getCode());
        exec.setSupportDays(String.valueOf(day));
        exec.setActualPayAmt(exec.getDiscountsAmt() * day);
        exec = supportApplicationExecutionRepository.saveAndFlush(exec);

        SupportApplicationItem item = supportApplicationItemRepository.findOne(exec.getSupportApplicationItem().getId());

        //结束日期大于开始日期为终止单据作废
        if(exec.getEndDate().getTime() < exec.getStartDate().getTime()){
            item.setRepeal(true);
            supportApplicationService.zzRYXX(Arrays.asList(exec));
        }else if(DateUtil.dateCompare(exec.getEndDate(),date) <= 0 ||
                (DateUtil.dateCompare(exec.getEndDate(), date) == 0 && (exec.getEndTime().getCode().equals("AM") && time.equals("PM")))){
            //终止并生成确认单
            supportApplicationService.zzRYXX(Arrays.asList(exec));
            affirmTask(exec,item);
        }

        SupportApplication supportApplication = item.getSupportApplication();
        supportApplication.setLastUpdatedStamp(new Date());
        supportApplicationRepository.saveAndFlush(supportApplication);

        //重新计算收费金额
//        exec.setTollTotalAmt(exec.getTollAmt() * day);
//        exec.setDiscountsTotalAmt(exec.getDiscountsAmt() * day);
        return exec;
    }


    /**
     * 延期或者终止审核拒绝
     * @return
     */
    public SupportApplicationExecution approveRefuse(SimpleRequest request){
        SupportApplicationExecution execution = request.getO(SupportApplicationExecution.class);
        execution.setEndDatePre(null);
        execution.setEndTimePre(null);
        return supportApplicationExecutionRepository.saveAndFlush(execution);
    }

    /**
     * 根据执行表内容生成确认单
     */
    public void affirmTask(SupportApplicationExecution execution,SupportApplicationItem item){
        if (item.getSupportApplicationAffirms().isEmpty()){
            //如果关联的确认单是空的说明，支援总天数不够七天，支援结束后生成
            //算出相差的天数 减1 开始当天和结束当天不算，后面计算
            long betweenDays = (execution.getEndDate().getTime() - execution.getStartDate().getTime()) / (1000L*3600L*24L) - 1;
            //支援时长
            double day = supportApplicationAffirmService.calculateDay(betweenDays, execution.getStartTime().getCode(), execution.getEndTime().getCode());
            SupportApplicationAffirm affirm = supportApplicationAffirmService.insertAffirm(execution,day,execution.getStartDate(), execution.getStartTime(), execution.getEndDate(), execution.getEndTime());
            //生成确认单后转OA
            this.invoke("hr.supportApplicationAffirm.transferOA",affirm);
        }else {
            List<SupportApplicationAffirm> affirms = item.getSupportApplicationAffirms();
            affirms = affirms.stream().sorted(Comparator.comparing(SupportApplicationAffirm::getEndDate).reversed()).collect(Collectors.toList());
            SupportApplicationAffirm affirm = affirms.get(0);
            //如果已经有生成确认单，执行表的结束日期减去上一张单的日期 大于0 说明还需要生成确认单
            if (DateUtil.dateCompare(execution.getEndDate(), affirm.getEndDate()) > 0){
                if (affirm.getEndTime().getCode().equals("AM")){
                    Enumeration startTime = enumerationRepository.findByCodeAndValidIsTrue("PM");
                    //算出相差的天数 减1 开始当天和结束当天不算，后面计算
                    long betweenDays = (execution.getEndDate().getTime() - affirm.getEndDate().getTime()) / (1000L*3600L*24L) - 1;
                    double day = supportApplicationAffirmService.calculateDay(betweenDays, "PM", execution.getEndTime().getCode());
                    SupportApplicationAffirm insertAffirm = supportApplicationAffirmService.insertAffirm(execution, day,
                            affirm.getEndDate(), execution.getStartTime(), execution.getEndDate(), execution.getEndTime());
                    //生成确认单后转OA
                    this.invoke("hr.supportApplicationAffirm.transferOA",insertAffirm);
                }else if(affirm.getEndTime().getCode().equals("PM")){
                    //当前时间 + 1 已有确认单的结束时间为下午 新确认单为开始时间为次日早上
                    Date newDate = DateUtil.add(affirm.getEndDate(), Calendar.DATE, 1);
                    Enumeration startTime = enumerationRepository.findByCodeAndValidIsTrue("AM");
                    //新开始的时间比执行表里的时间小 说明支援单还没有结束
                    //算出相差的天数 减2 开始当天和结束当天不算，后面计算
                    long betweenDays = (execution.getEndDate().getTime() - newDate.getTime()) / (1000L*3600L*24L) - 1;
                    //上下午天数计算 得到准确的时间
                    double day = supportApplicationAffirmService.calculateDay(betweenDays,"AM",execution.getEndTime().getCode());
                    //生成确认单 开始时间应该为前面那张单的结束时间的下一个时间段
                    SupportApplicationAffirm insertAffirm = supportApplicationAffirmService.insertAffirm(execution, day,
                            newDate, startTime, execution.getEndDate(), execution.getEndTime());
                    //生成确认单后转OA
                    this.invoke("hr.supportApplicationAffirm.transferOA",insertAffirm);
                }
                //执行表日期和上张确认单是同一天
            }else if(DateUtil.dateCompare(execution.getEndDate(), affirm.getEndDate()) == 0){
                //如果上下午不相等说明还需要生成一张0.5天的确认单
                if(execution.getEndTime().getCode().equals(affirm.getEndTime().getCode())){
                    if (affirm.getEndTime().getCode().equals("AM")){
//                        BusinessAttributeValue startTime = businessAttributeValueRepository.findByCode("PM");
                        //算出相差的天数 减2 开始当天和结束当天不算，后面计算
                        long betweenDays = (execution.getEndDate().getTime() - affirm.getEndDate().getTime()) / (1000L*3600L*24L) - 1;
                        double day = supportApplicationAffirmService.calculateDay(betweenDays, "PM", execution.getEndTime().getCode());
                        SupportApplicationAffirm insertAffirm = supportApplicationAffirmService.insertAffirm(execution, day,
                                affirm.getEndDate(), execution.getStartTime(), execution.getEndDate(), execution.getEndTime());
                        //生成确认单后转OA
                        this.invoke("hr.supportApplicationAffirm.transferOA",insertAffirm);
                    }
                }
            }
        }
    }

    /**
     * 定时任务执行 支援结束 下午结束 次日凌晨跑定时任务
     * @param request
     */
    public void afterSupportFinish(SimpleRequest request){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        //今天
        Date today= formatter.parse(formatter.format(date),new ParsePosition(0));
        //昨天
        Date yesterday = DateUtil.parse( DateUtil.format(DateUtil.add(today, Calendar.DATE, -1),DateUtil.SHOW_DATE_FORMAT)+" 12:00:00",DateUtil.SHOW_DATETIME_FORMAT);
        List<SupportApplicationExecution> listEnd = supportApplicationExecutionRepository.findByEndDatePM(yesterday, today);
        if(listEnd.size()>0){
            supportApplicationService.zzRYXX(listEnd);
            listEnd.forEach(execution -> {
                SupportApplicationItem item = supportApplicationItemRepository.findOne(execution.getSupportApplicationItem().getId());
                //生成确认单任务
                affirmTask(execution,item);
                SupportApplication supportApplication = item.getSupportApplication();
                supportApplication.setLastUpdatedStamp(new Date());
                supportApplicationRepository.saveAndFlush(supportApplication);
            });
        }
    }

    /**
     * 定时任务执行 支援结束 上午结束 12点后跑定时任务
     * @param request
     */
    public void forenoonSupportFinish(SimpleRequest request){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        //今天
        Date today= formatter.parse(formatter.format(date),new ParsePosition(0));
        //今天中午
        Date todayNoon = DateUtil.parse( DateUtil.format(today,DateUtil.SHOW_DATE_FORMAT)+" 12:00:00",DateUtil.SHOW_DATETIME_FORMAT);
        List<SupportApplicationExecution> listEnd = supportApplicationExecutionRepository.findByEndDateAM(today, todayNoon);
        if(listEnd.size()>0){
            supportApplicationService.zzRYXX(listEnd);
            listEnd.forEach(execution -> {
                SupportApplicationItem item = supportApplicationItemRepository.findOne(execution.getSupportApplicationItem().getId());
                //生成确认单任务
                affirmTask(execution,item);
                SupportApplication supportApplication = item.getSupportApplication();
                supportApplication.setLastUpdatedStamp(new Date());
                supportApplicationRepository.saveAndFlush(supportApplication);
            });
        }
    }

    /**
     * 定时任务执行 支援生效 开始时间为上午的 凌晨跑定时任务
     * @param request
     */
    public void forenoonSupportEffect(SimpleRequest request){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        //今天
        Date today= formatter.parse(formatter.format(date),new ParsePosition(0));
        //今天中午
        Date todyNoon = DateUtil.parse( DateUtil.format(today,DateUtil.SHOW_DATE_FORMAT)+" 12:00:00",DateUtil.SHOW_DATETIME_FORMAT);
        //查询开始为今天 小于 今天中午12:00 的为上午需要执行生效的单据
        List<SupportApplicationExecution> listExec = supportApplicationExecutionRepository.findByStartDateAM(today, todyNoon);
        if(listExec.size()>0){
            supportApplicationService.updateRYXX(listExec);
            listExec.forEach(execution -> {
                SupportApplicationItem item = supportApplicationItemRepository.findOne(execution.getSupportApplicationItem().getId());
                SupportApplication supportApplication = item.getSupportApplication();
                supportApplication.setLastUpdatedStamp(new Date());
                supportApplicationRepository.saveAndFlush(supportApplication);
            });
        }
    }

    /**
     * 定时任务执行 支援生效 开始时间为下午的 12点后跑定时任务
     * @param request
     */
    public void noonSupportEffect(SimpleRequest request){
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        //今天
        Date today= formatter.parse(formatter.format(date),new ParsePosition(0));
        //今天中午
        Date todyNoon = DateUtil.parse( DateUtil.format(today,DateUtil.SHOW_DATE_FORMAT)+" 12:00:00",DateUtil.SHOW_DATETIME_FORMAT);
        //明天
        Date tomorrow = DateUtil.add(today, Calendar.DATE, 1);
        //查询 开始时间为今天中午12:00到明天   的为下午需要执行生效的单据
        List<SupportApplicationExecution> listExec = supportApplicationExecutionRepository.findByStartDatePM(todyNoon, tomorrow);
        if(listExec.size()>0){
            supportApplicationService.updateRYXX(listExec);
            listExec.forEach(execution -> {
                SupportApplicationItem item = supportApplicationItemRepository.findOne(execution.getSupportApplicationItem().getId());
                SupportApplication supportApplication = item.getSupportApplication();
                supportApplication.setLastUpdatedStamp(new Date());
                supportApplicationRepository.saveAndFlush(supportApplication);
            });
        }
    }

    /**
     * 检查计费支援单冲突问题
     */
    public void checkSupportClash(SupportApplicationExecution execution){
        //没有执行的支援单从支援人员明细取
        List<SupportApplicationItem> supports = supportApplicationItemRepository.findBySupportUidAndIconExecuteAndRepeal(execution.getSupportUid(),false,false);
        if (!supports.isEmpty()){
            SupportApplicationItem oldItem = supports.get(selectLastOne2(supports));
            //新单的生效日期小于等于旧单的生效日期 && 新单的结束支援日期 大于 旧单生效日期 提示
            if(execution.getStartDate().getTime()<= oldItem.getStartDate().getTime()
                    && execution.getEndDatePre().getTime()> oldItem.getStartDate().getTime()){
                throw new RuntimeException(execution.getSupportUid().getName() +"与支援申请单：" + oldItem.getSupportApplication().getId() + "冲突！支援前不可支援！");
                //新单的生效日期大于旧单的生效日期 && 新单的生效日期 小于等于 旧单支援结束日期
            } else if (execution.getStartDate().getTime() >oldItem.getStartDate().getTime()
                    &&execution.getStartDate().getTime()<= oldItem.getEndDate().getTime() ){
                throw new RuntimeException(execution.getSupportUid().getName() +"与支援申请单：" + oldItem.getSupportApplication().getId() + "冲突！不可在支援期间支援！");
                //新单的生效日期小于旧单的生效日期 && 新单的支援结束日期 大于 旧单支援结束日期
            } else if (execution.getStartDate().getTime() < oldItem.getStartDate().getTime()
                    &&execution.getEndDatePre().getTime() > oldItem.getEndDate().getTime() ){
                throw new RuntimeException(execution.getSupportUid().getName() +"与支援申请单：" + oldItem.getSupportApplication().getId() + "冲突！不可在支援期间支援！");
                //新单的生效日期小于等于旧单的生效日期 && 新单的结束支援日期大于等于旧单的生效日期
            }else if (execution.getStartDate().getTime() <= oldItem.getStartDate().getTime()
                    && execution.getEndDate().getTime() >= oldItem.getStartDate().getTime()){
                throw new RuntimeException(execution.getSupportUid().getName() +"与支援申请单：" + oldItem.getSupportApplication().getId() + "冲突！");
            }
        }

        //已经执行的支援单从执行表里取数
        List<SupportApplicationExecution> listExec = supportApplicationExecutionRepository.findBySupportApplication(execution.getSupportUid().getId());

        //过滤当前计费支援单
        listExec = listExec.stream().filter(exec -> {return !exec.getId().equals(execution.getId());}).collect(Collectors.toList());

        if(!listExec.isEmpty()){
            listExec.stream().forEach(exec -> {
                if(execution.getStartDate().getTime() <= exec.getStartDate().getTime() && execution.getStartDate().getTime() > exec.getEndDate().getTime()){
                    throw new RuntimeException(execution.getSupportUid().getName() +"与付费支援申请单：" + exec.getSupportApplicationItem().getSupportApplication().getId() + "冲突！支援前不可支援！");
                } else if (execution.getStartDate().getTime() >exec.getStartDate().getTime()
                        &&execution.getStartDate().getTime()< exec.getEndDate().getTime() ){
                    throw new RuntimeException(execution.getSupportUid().getName() +"与付费支援申请单：" + exec.getSupportApplicationItem().getSupportApplication().getId() + "冲突！不可在支援期间支援！");
                    //新单的生效日期小于旧单的生效日期 && 新单的支援结束日期 大于 旧单支援结束日期
                } else if (execution.getStartDate().getTime() < exec.getStartDate().getTime()
                        &&execution.getEndDatePre().getTime() > exec.getEndDate().getTime() ){
                    throw new RuntimeException(execution.getSupportUid().getName() +"与付费支援申请单：" + exec.getSupportApplicationItem().getSupportApplication().getId() + "冲突！不可在支援期间支援！");
                    //新单的生效日期小于等于旧单的生效日期 && 新单的结束支援日期大于等于旧单的生效日期
                }else if (execution.getStartDate().getTime() <= exec.getStartDate().getTime()
                        && execution.getEndDatePre().getTime() >= exec.getStartDate().getTime()){
                    throw new RuntimeException(execution.getSupportUid().getName() +"与付费支援申请单：" + exec.getSupportApplicationItem().getSupportApplication().getId() + "冲突！");
                }
            });
        }

        //根据计费支援单的开始时间判断是否和调动单有冲突
        List<TransferApplicationItem>  timeOutItems = transferApplicationItemRepository.findByTransferUidAndIconExecuteAndEffectiveDate(execution.getSupportUid(),true,execution.getStartDate());
        if (!timeOutItems.isEmpty()){
            timeOutItems.forEach(timeOutItem->{
                if (timeOutItem.getTransferApplications().getHrTransferType().equals("000102")){
                    throw new RuntimeException(execution.getSupportUid().getName() +"与调动申请单：" + timeOutItems.get(timeOutItems.size()-1).getTransferApplications().getId() + "冲突");
                }
            });
        }

        //未执行且未废除的调动 支援单
        List<TransferApplicationItem>  Items = transferApplicationItemRepository.findByTransferUidAndIconExecute(execution.getSupportUid(),false);
        List<TransferApplicationItem>  itemList= new ArrayList<>();
        if (!Items.isEmpty()){
            Items.forEach(Item->{
                String state= Item.getTransferApplications().getState();
                if (!(state.equals("repeal")||state.equals("delete"))&&!Item.isRepeal()){
                    itemList.add(Item);
                }
            });
        }

        //执行还未结束支援的支援单
        List<TransferApplicationItem> supItemList =  transferApplicationItemRepository.findByTransferUidAndIconExecute(execution.getSupportUid(),true);
        if(!supItemList.isEmpty()){
            supItemList.forEach(supItem->{
                if (supItem.getTransferApplications().getHrTransferType().getId().equals("000103")
                        && !supItem.getHrTransferKind().getId().equals("000430") //不等于临时调工号
                        && supItem.getEndDate().getTime() > new Date().getTime()
                        && supItem.getTransferUid().equals(execution.getSupportUid())
                        &&( !supItem.getTransferApplications().getState().equals("repeal")
                        || !supItem.getTransferApplications().getState().equals("delete"))
                        &&!supItem.isRepeal()){
                    itemList.add(supItem);
                }
            });
        }

        if (!itemList.isEmpty()){
            TransferApplicationItem oldItem = itemList.get(selectLastOne(itemList));
            String oldType =oldItem.getTransferApplications().getHrTransferType().getId();
            if(oldType.equals("000102")){
                //新单的生效日期小于等于旧单的生效日期 && 新单的支援结束日期 大于等于 旧单生效日期
                if (execution.getStartDate().getTime() <= oldItem.getEffectiveDate().getTime()&&
                        execution.getEndDatePre().getTime() >= oldItem.getEffectiveDate().getTime()){
                    throw new RuntimeException( execution.getSupportUid().getName() +"与调动申请单：" + oldItem.getTransferApplications().getId() + "冲突");
                }
            }else if (oldType.equals("000103")){
                //新单的生效日期小于等于旧单的生效日期 && 新单的结束支援日期 大于 旧单生效日期 提示
                if(execution.getStartDate().getTime()<= oldItem.getEffectiveDate().getTime()
                        && execution.getEndDatePre().getTime()> oldItem.getEffectiveDate().getTime()){
                    throw new RuntimeException(execution.getSupportUid().getName() +"与支援申请单：" + oldItem.getTransferApplications().getId() + "冲突！支援前不可支援！");
                    //新单的生效日期大于旧单的生效日期 && 新单的生效日期 小于等于 旧单支援结束日期
                } else if (execution.getStartDate().getTime() >oldItem.getEffectiveDate().getTime()
                        &&execution.getStartDate().getTime()<= oldItem.getEndDate().getTime() ){
                    throw new RuntimeException(execution.getSupportUid().getName() +"与支援申请单：" + oldItem.getTransferApplications().getId() + "冲突！不可在支援期间支援！");
                    //新单的生效日期小于旧单的生效日期 && 新单的支援结束日期 大于 旧单支援结束日期
                } else if (execution.getStartDate().getTime() < oldItem.getEffectiveDate().getTime()
                        &&execution.getEndDatePre().getTime() > oldItem.getEndDate().getTime() ){
                    throw new RuntimeException(execution.getSupportUid().getName() +"与支援申请单：" + oldItem.getTransferApplications().getId() + "冲突！不可在支援期间支援！");
                    //新单的生效日期小于等于旧单的生效日期 && 新单的结束支援日期大于等于旧单的生效日期
                }else if (execution.getStartDate().getTime() <= oldItem.getEffectiveDate().getTime()
                        && execution.getEndDatePre().getTime() >= oldItem.getEffectiveDate().getTime()){
                    throw new RuntimeException(execution.getSupportUid().getName() +"与支援申请单：" + oldItem.getTransferApplications().getId() + "冲突！");
                }
            }
        }
    }

    /**
     * 创建日期最大的明细
     * @param list
     * @return
     */
    private int selectLastOne(List<TransferApplicationItem> list) {
        int index = 0;
        Long dates[] = new Long[list.size()];
        for (int i = 1; i <= list.size(); i++) {
            // 把date类型的时间对象转换为long类型，时间越往后，long的值就越大，
            // 所以就依靠这个原理来判断距离现在最近的时间
            dates[i - 1] = list.get(i-1).getCreateDate().getTime();
        }

        Long maxIndex = dates[0];// 定义最大值为该数组的第一个数
        for (int j = 0; j < dates.length; j++) {
            if (maxIndex < dates[j]) {
                maxIndex = dates[j];
                // 找到了这个j
                index = j;
            }
        }
        return index;
    }

    /**
     * 创建日期最大的明细
     * @param list
     * @return
     */
    private int selectLastOne2(List<SupportApplicationItem> list) {
        int index = 0;
        Long dates[] = new Long[list.size()];
        for (int i = 1; i <= list.size(); i++) {
            // 把date类型的时间对象转换为long类型，时间越往后，long的值就越大，
            // 所以就依靠这个原理来判断距离现在最近的时间
            dates[i - 1] = list.get(i-1).getCreateDate().getTime();
        }

        Long maxIndex = dates[0];// 定义最大值为该数组的第一个数
        for (int j = 0; j < dates.length; j++) {
            if (maxIndex < dates[j]) {
                maxIndex = dates[j];
                // 找到了这个j
                index = j;
            }
        }
        return index;
    }
}
